#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include <cstdlib>
#include <functional>
#include "log.hpp"

namespace zxf
{
    void hander(const int fd)
    {
        for (;;)
        {
            char buf[1024] = {0};
            size_t len = sizeof(buf);
            bzero(buf, len);
            ssize_t t = read(fd, buf, len);
            if (t < 0)
            {
                std::cout << "read error , exit" << std::endl;
                logMessage(ERROR, "%s:%d", "task.hpp: read error , exit", 0);
                exit(READ_ERR);
            }
            else if (t == 0)
            {
                //std::cout << "断开链接 " << std::endl;
                logMessage(NORMAL, "%s:%d", "task.hpp: 断开链接", 0);
                // 关闭文件描述符(link_sock)
                close(fd);
                break; // 函数退出
            }
            else
            {
                // 处理收到的信息
                //std::cout << buf << std::endl;
                std::string str = "server get:";
                str += buf;
                int ret = write(fd, str.c_str(), str.length());
                if (ret == -1)
                {
                    //std::cout << "write error , exit" << std::endl;
                    logMessage(ERROR, "%s:%d", "task.hpp: write error , exit!!", 0);
                    exit(WRITE_ERR);
                }
            }
        }
    }
    

    class Task
    {
    public:
        using fun_t = std::function<void(const int)>;
        Task()
        {
        }
        Task(int fd, fun_t func = hander) : _fd(fd), _func(func)
        {
        }
        //()重载
        void operator()()
        {
            _func(_fd);
        }

    private:
        int _fd;
        fun_t _func;
    };
} // namespace zxf end !!
